<template>
    <div
        ref="editor"
        class="input-box"
        :contenteditable="contenteditable"
        @keydown.stop
        @input="inputText"
        @paste="handleParse"
    ></div>
</template>
<script>
    export default {
        name: "ScDivTextArea",
        props: {
            value: {
                type: String
            }, // 父组件v-model绑定的prop
            contenteditable: {
                type: Boolean,
                default: true
            }
        },
        data() {
            return {
                isSelfChange: false // 解决赋值时光标自动定位到起始位置
            };
        },
        methods: {
            // 1、监听输入框内容
            inputText() {
                console.log("inputText");
                this.isSelfChange = true;
                this.$emit("input", this.$refs.editor.innerHTML);
            },
            //处理粘贴内容，不能输入Html
            handleParse(event) {
                let paste = (event.clipboardData || window.clipboardData).getData(
                    "text"
                );

                const selection = window.getSelection();
                if (!selection.rangeCount) return false;
                selection.deleteFromDocument();
                const range = selection.getRangeAt(0);
                range.insertNode(document.createTextNode(paste));
                range.setStart(range.endContainer, range.endOffset);
                // 将选区折叠为一个光标
                event.preventDefault();
                this.inputText();
            },
            /** 根据dom修改html的值 */
            initDom(val) {
                this.$refs.editor.innerHTML = val;
                this.focus();
            },
            focus() {
                this.$refs.editor.focus();
                // console.log("将光标移动到输入框最后");
                const selection = getSelection();
                // 清除选定对象的所有光标对象
                selection.removeAllRanges();
                var atRange = document.createRange();
                atRange.selectNodeContents(this.$refs.editor);
                // 光标移动到到原来的位置加上新内容的长度
                atRange.setStart(
                    this.$refs.editor,
                    this.$refs.editor.childNodes.length
                );
                // 光标开始和光标结束重叠
                atRange.collapse(true);
                // 插入新的光标对象
                selection.addRange(atRange);
            }
        },
        watch: {
            value(val) {
                //当输入后，设置了isSelfChange，但是再外边改变，还没走到这里
                if (this.isSelfChange) {
                    this.isSelfChange = false;
                    return;
                }
                this.initDom(val);
            }
        },
        mounted() {
            this.initDom(this.value);
        }
    };
</script>
<style lang="scss" scoped>
    @import "@/styles/variables.scss";
    div[contenteditable]:empty:before {
        content: attr(placeholder);
        color: $textInfo3;
    }
</style>
